import gdata.youtube
import gdata.youtube.service

import urllib2
import errno
import os
import time
from sys import argv, exit


def fixYTLink(url):
    url = urllib2.unquote(url)
    url = url.replace('generate_204','videoplayback')
    url = url.replace('\\','')
    url = url.replace('u0026','&')
    return url

def sanitizeFileName(file_name):
    file_name = file_name.replace('<','')
    file_name = file_name.replace('>','')
    file_name = file_name.replace(':','')
    file_name = file_name.replace('"','')
    file_name = file_name.replace('/','')
    file_name = file_name.replace('\\','')
    file_name = file_name.replace('|','')
    file_name = file_name.replace('?','')
    file_name = file_name.replace('*','')
    file_name = file_name.replace(' ','_')
    return file_name

def downloadYTVid(url, file_name, desired_speed):
    u = urllib2.urlopen(url)
    try:
        f= open(file_name, 'wb')
        meta = u.info()
        file_size = int(meta.getheaders("Content-Length")[0])
        print "Downloading: %s Bytes: %s" % (file_name, file_size)

        file_size_dl = 0
        block_sz = 8192
        begin = time.clock()
        while True:
            buffer = u.read(block_sz)
            if not buffer:
                break
            after_read = time.clock()
            file_size_dl += len(buffer)
            f.write(buffer)
            speed = file_size_dl / (after_read - begin)
            while speed > desired_speed:
                after_read = time.clock()
                speed = file_size_dl / (after_read - begin)
            status = r"%10d  [%3.2f%%]  %5d Bytes/S" % (file_size_dl, file_size_dl * 100. / file_size, speed)
            status = status + chr(8)*(len(status)+1)
            print status,
        f.close()
    except IOError:
        f.close()
        exit()

def queryEntry(entry,content, desired_speed):
    if entry.media.category[0].text == 'Games':
        title = entry.media.title.text
        title = sanitizeFileName(title)
        name = title+'.mp4'
        if name not in content:
            link = entry.media.player.url
            html = urllib2.urlopen(link+'&hd=1').read()
            start = html.find('img.src = "')
            end = html.find('"',start+11)
            y = html[start+11:end]
            y = fixYTLink(y)
            t = time.localtime()
            if t[3] > 19 or t[3] < 2:
                downloadYTVid(y,name, 500 * 1024)
            else:
                downloadYTVid(y,name, desired_speed)
            try:
                f = open('video_entries.txt','a')
                f.write(time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()) + ' === Downloaded video ' + name + ' published on: ' + entry.published.text + '\n')
                f.close()
            except IOError:
                f.close()
                exit()

def queryVideoFeed(feed, counter, content, desired_speed):
    for entry in feed.entry:
        queryEntry(entry,content, desired_speed)
        counter = counter + 1
    return counter

def downloadYTFeed(uri, desired_speed):
    querya = '?start-index='
    queryb = '&max-results=50'
    yt_service = gdata.youtube.service.YouTubeService()
    count = 0
    rc = 1
    try:
        f = open('video_entries.txt','r')
        content = f.read()
    except IOError as e:
        if e.errno != errno.ENOENT:
            f.close()
            exit()
        content = ''
    while 0 < 1:
        print count
        s = '%s%s%d%s' % (uri,querya,(count+1),queryb)
        feed = yt_service.GetYouTubeVideoFeed(s)
        rc = queryVideoFeed(feed, count, content, desired_speed)
        if count == rc:
            break
        else:
            count = rc

try:
    user = argv[1]
except IndexError:
    print '\nSyntax:python snap.py [username] [Speed]'
    print '...Using directory name as user name...Done'
    path = os.getcwd()
    user = path[path.rfind('\\')+1:]
    print '...User = %s\n' % user
try:
    desired_speed = int(argv[2])
except IndexError:
    print '\nSyntax:python snap.py [username] [Speed]'
    print '...Setting maximum speed to default value 1024 KB/s...Done'
    desired_speed = 1024
uri = 'http://gdata.youtube.com/feeds/api/users/' + user + '/uploads'
downloadYTFeed(uri, desired_speed * 1024)
